package com.admin.system.service.impl;

import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.handler.PageResultHandler;
import com.admin.model.base.PageResult;
import com.admin.model.dto.JobDto;
import com.admin.model.pojo.Dept;
import com.admin.model.pojo.Job;
import com.admin.system.dao.JobDao;
import com.admin.system.dao.UserDao;
import com.admin.system.security.service.UserDetailsServiceImpl;
import com.admin.system.service.JobService;
import com.admin.system.service.mapstruct.JobMapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * (Job)表服务实现类
 *
 * @author makejava
 * @since 2021-01-31 20:22:08
 */
@CacheConfig(cacheNames = "job")
@Service("jobService")
public class JobServiceImpl extends ServiceImpl<JobDao, Job> implements JobService {
    @Resource
    private JobDao jobDao;
    @Resource
    private UserDao userDao;
    @Resource
    private JobMapper jobMapper;

    @Override
    public Job create(JobDto jobDto) {
        Job job = jobMapper.toEntity(jobDto);
        Optional<Job> optional = new LambdaQueryChainWrapper<>(jobDao)
                .select(Job::getId)
                .eq(Job::getName, job.getName())
                .last("limit 1")
                .oneOpt();

        Assert.isTrue(optional.isPresent(), "岗位名称重复");
        int insert = jobDao.insert(job);
        Assert.isTrue(insert > 0, "创建失败");
        return jobDao.selectById(job.getId());
    }

    @Override
    public JobDto findById(Long id) {
        return jobMapper.toDto(jobDao.selectById(id));
    }

    //@Cacheable(key = "'jobs'+#pageSize", unless = "#pageNum>0")
    @Override
    public PageResult queryAll(JobDto jobDto, int pageNum, int pageSize, String sort) {
        Job job = jobMapper.toEntity(jobDto);
        Page<Job> page = PageHelper.startPage(pageNum, pageSize, StrUtil.toUnderlineCase(sort)).doSelectPage(()->{
            jobDao.queryAll(job);
        });
        return PageResult.builder()
                .total(page.getTotal())
                .rows(jobMapper.toDto(page.getResult()))
                .build();
    }

    @Override
    public List<LinkedHashMap<String, Object>> findList() {
        List<Job> list = new LambdaQueryChainWrapper<>(jobDao).select(Job::getId, Job::getName, Job::getEnabled).list();
        return list.stream().map(job -> {
                    LinkedHashMap<String, Object> map = new LinkedHashMap<>();
                    map.put("value", job.getId().toString());
                    map.put("label", job.getName());
                    map.put("disabled", !job.getEnabled());
                    return map;
                }
        ).collect(Collectors.toList());
    }

    //@CacheEvict(key = "'jobs'", allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteByIds(Set<Long> ids) {
        for (Long id : ids) {
            int delete = jobDao.deleteById(id);
            if (delete > 0) {
                // 删除用户授权岗位
                userDao.delAuthJobByJobId(id);
            }
        }
        //删除所有用户缓存
        UserDetailsServiceImpl.clearCachUserAll();
    }

    @Override
    public Job updateById(JobDto jobDto) {
        Job job = jobMapper.toEntity(jobDto);
        int insert = jobDao.updateById(job);
        Assert.isTrue(insert > 0, "更新失败");
        //删除所有用户缓存
        UserDetailsServiceImpl.clearCachUserAll();
        return jobDao.selectById(job.getId());
    }

}